<?php
declare (strict_types = 1);

namespace app\index\controller;

use app\index\BaseController;
use app\index\model\Article;
use app\index\model\Block;
use app\index\model\Topic as TopicModel;
use think\facade\Log;

class Topic extends BaseController
{
    //中间件
    protected $middleware = [
        'method:ajax' => ['only'=>['list']]
    ];

    //显示资源列表
    public function index()
    {
        $where = [];
        $category_id = input('category_id/d');
        if ($category_id){
            $where[] = ['category_id','=', $category_id];
        }
        return view('index',[
            'count'=> TopicModel::getCount($where),
            'limit'=> TopicModel::LIMIT_NUM,

            'crumb' => [
                'home'     => '/',
                '话题列表'  => request()->url()
            ]
        ]);
    }

    //列表数据
    public function list(){
        try{
            //构建条件
            $where = [];

            //获取参数
            $name = input('name/s');
            if ($name){
                $where[] = ['name','like', '%'.$name.'%'];
            }
            $status = input('status/s');
            if ($status === '0' || $status === '1'){
                $where[] = ['status','=', $status];
            }
            $category_id = input('category_id/d');
            if ($category_id){
                $where[] = ['category_id','=', $category_id];
            }
            $user_id = input('user_id/d');
            if ($user_id){
                $where[] = ['user_id','=', $user_id];
            }




            //获取参数
            $page = input('page/d');
            $limit= input('limit/d');
            $data = TopicModel::getList($page, $limit, $where);

            return json([
                'code' => 0,
                'data'  => $data
            ]);
        }catch (\Exception $e){
            //Log::error($e->getMessage());
            return json([
                'code' => 1,
                'msg'  => $e->getMessage()
            ]);
        }
    }



    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read(int $id)
    {
        $model = $this->getModel(TopicModel::class, $id,['user','category']);
        return view('read',[
            'topic' => $model,

            //文章列表
            'count' => Article::getCount(['topic_id'=>$id]),
            'limit' => Article::LIMIT_NUM,


            'crumb' => [
                'home'     => '/',
                '话题列表'  => (string) url('index'),
                $model->name  => request()->url()
            ],

            //*热门文章
            'activeArticles' => Block::getActiveArticles(),
            //*推荐话题
            'activeTopics' => Block::getActiveTopics(),
        ]);
    }


}
